'use strict';
const fiip = require('fiip');
const Link = fiip.Link;

const startServer = (ip, port) => {
  const net = require('net');
  const link = new Link.Client();
  link.type = Link.type.tcp;
  link.status = Link.status.server;
  link.address = ip;
  link.port = port;
  link.fd = net.createServer();
  link.fd.listen(link.port);
  link.send = (data, dataLen, link) => {
    if (this.type == Link.type.tcp) this.fd.write(data.slice(0, dataLen));
    else link.fd.write(data.slice(0, dataLen));
  };
  link.recv = fiip.recv.bind(fiip);

  link.fd.on('connection', (socket) => {
    let rlink = new Link.Client();
    rlink.type = Link.type.tcp;
    rlink.status = Link.status.temp;
    rlink.address = socket.remoteAddress;
    rlink.port = socket.remotePort;
    rlink.fd = socket;
    rlink.send = link.send.bind(rlink);
    rlink.recv = link.recv;

    rlink.fd.on('data', (data) => {
      rlink.recv(data, data.length, rlink);
    });
    rlink.fd.on('error', (error) => {
      console.error('fiip-link-tcp/server: client error:', error);
    });
    rlink.fd.on('close', () => {
      console.error('fiip-link-tcp/server: client close');
    });
  });
  link.fd.on('error', (error) => {
    console.error('fiip-link-tcp/server: error:', error);
  });
  link.fd.on('close', () => {
    console.error('fiip-link-tcp/server: close');
  });

  return link;
};

module.exports = startServer;
